/**
 * 模型选择器组件
 * 允许用户选择和配置AI模型
 */

import React, { useState, useEffect } from 'react';
import { Select, Card, Badge, Tooltip, Space, Button, Modal, Form, Input, Slider } from 'antd';
import { SettingOutlined, ThunderboltOutlined, DollarOutlined, GlobalOutlined } from '@ant-design/icons';
import { simpleMultiModelService } from '../../services/simple-multi-model.service';

const { Option } = Select;

export interface ModelSelectorProps {
  selectedModel?: string;
  onModelChange: (model: string) => void;
  onConfigChange?: (config: any) => void;
  showHealthStatus?: boolean;
  showAdvancedOptions?: boolean;
  taskType?: 'creative' | 'technical' | 'analysis' | 'general' | 'chinese';
}

export interface ModelConfigModalProps {
  visible: boolean;
  modelName: string;
  onOk: (config: any) => void;
  onCancel: () => void;
}

const ModelConfigModal: React.FC<ModelConfigModalProps> = ({
  visible,
  modelName,
  onOk,
  onCancel
}) => {
  const [form] = Form.useForm();

  const handleOk = () => {
    form.validateFields().then(values => {
      onOk(values);
      form.resetFields();
    });
  };

  return (
    <Modal
      title={`配置 ${modelName} 模型`}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          temperature: 0.7,
          maxTokens: 4096,
          timeout: 30000
        }}
      >
        <Form.Item
          name="temperature"
          label="创造性 (Temperature)"
          help="控制输出的随机性，0-1之间，值越高越有创造性"
        >
          <Slider
            min={0}
            max={1}
            step={0.1}
            marks={{
              0: '保守',
              0.5: '平衡',
              1: '创新'
            }}
          />
        </Form.Item>

        <Form.Item
          name="maxTokens"
          label="最大输出长度"
          help="生成内容的最大token数量"
        >
          <Slider
            min={100}
            max={8192}
            step={100}
            marks={{
              100: '100',
              2048: '2K',
              4096: '4K',
              8192: '8K'
            }}
          />
        </Form.Item>

        <Form.Item
          name="timeout"
          label="超时时间 (毫秒)"
          help="请求超时时间"
        >
          <Input type="number" min={5000} max={60000} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export const ModelSelector: React.FC<ModelSelectorProps> = ({
  selectedModel,
  onModelChange,
  onConfigChange,
  showHealthStatus = true,
  showAdvancedOptions = false,
  taskType = 'general'
}) => {
  const [availableModels, setAvailableModels] = useState<string[]>([]);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [configModalModel, setConfigModalModel] = useState<string>('GPT-4');

  // 获取可用模型列表
  useEffect(() => {
    const models = simpleMultiModelService.getAvailableModels();
    setAvailableModels(models);
  }, []);

  const handleConfigClick = (modelName: string) => {
    setConfigModalModel(modelName);
    setConfigModalVisible(true);
  };

  const handleConfigOk = (config: any) => {
    setConfigModalVisible(false);
    onConfigChange?.(config);
  };

  const getModelInfo = (modelName: string) => {
    // 简化的模型信息
    const modelInfo: Record<string, any> = {
      'GPT-4': { provider: 'OpenAI', cost: 0.03, maxTokens: 8192 },
      'GPT-3.5-Turbo': { provider: 'OpenAI', cost: 0.002, maxTokens: 4096 },
      'Claude-3-Sonnet': { provider: 'Anthropic', cost: 0.015, maxTokens: 100000 }
    };
    return modelInfo[modelName] || { provider: 'Unknown', cost: 0, maxTokens: 4096 };
  };

  return (
    <Card 
      title="模型选择" 
      size="small"
      extra={
        showAdvancedOptions && selectedModel && (
          <Button
            type="text"
            icon={<SettingOutlined />}
            onClick={() => handleConfigClick(selectedModel)}
          >
            配置
          </Button>
        )
      }
    >
      <Select
        style={{ width: '100%' }}
        placeholder="选择AI模型"
        value={selectedModel}
        onChange={onModelChange}
      >
        {availableModels.map(modelName => {
          const info = getModelInfo(modelName);
          return (
            <Option key={modelName} value={modelName}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Space>
                  <span>{modelName}</span>
                  <Tooltip title={`提供商: ${info.provider}`}>
                    <GlobalOutlined style={{ color: '#1890ff' }} />
                  </Tooltip>
                  <Tooltip title={`成本: $${info.cost}/1K tokens`}>
                    <DollarOutlined style={{ color: '#faad14' }} />
                  </Tooltip>
                  <Badge status="success" text="正常" />
                </Space>
              </div>
            </Option>
          );
        })}
      </Select>

      {selectedModel && (
        <div style={{ marginTop: 12, fontSize: '12px', color: '#666' }}>
          <Space split={<span>•</span>}>
            <span>最大长度: {getModelInfo(selectedModel).maxTokens}</span>
            <span>提供商: {getModelInfo(selectedModel).provider}</span>
            <span>成本: ${getModelInfo(selectedModel).cost}/1K tokens</span>
          </Space>
        </div>
      )}

      <ModelConfigModal
        visible={configModalVisible}
        modelName={configModalModel}
        onOk={handleConfigOk}
        onCancel={() => setConfigModalVisible(false)}
      />
    </Card>
  );
};
